package com.cac.demo.service.pointPackageSort;

import com.cac.demo.dao.msConsole.MsConsoleDao;
import com.cac.demo.dao.pointPackageSort.PointPackageDao;
import com.cac.demo.util.CreateCommonLog;


import com.cac.demo.util.adapter.ComUtil;
import com.cac.demo.util.adapter.ResponseMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @className: PointPackageSortService
 * @description: （描述这个类的作用）
 * @author:
 * @date: 2023/6/21 10:48:48 周三
 * @version: 1.0
 */
@Slf4j
@Service
public class PointPackageSortService {
    @Autowired
    private PointPackageDao pointPackageDao;
    @Autowired
    private MsConsoleDao msConsoleDao;
    @Autowired
    private CreateCommonLog createCommonLog;

    @Transactional
    public ResponseMsg<String> replaceMatchInfo(HashMap sourceMatch, List<HashMap> replaceMatchList){
        ResponseMsg responseMsg = new ResponseMsg();
        String toolCode = (String) sourceMatch.get("toolCode");
        int replaceQtys = 0;
        for(HashMap replaceMatch : replaceMatchList){
            if(replaceMatch.containsKey("replaceQty")&& Integer.parseInt(replaceMatch.get("replaceQty").toString())>0){
                String msAoMatchInfoId = ComUtil.getId();
                replaceMatch.put("msAoMatchInfoId",msAoMatchInfoId);
                replaceMatch.put("toolCode",toolCode);
                pointPackageDao.insertReplaceMaterial(replaceMatch);
                //插入一条 ms_assgin_workbintool_rel
                pointPackageDao.insertAssignWorkbinToolRelByMatchInfoId(replaceMatch);
                replaceQtys += Integer.parseInt(replaceMatch.get("replaceQty").toString());
            }
        }
        sourceMatch.put("replaceQtys",replaceQtys);
        pointPackageDao.updateSourceReplaceMatchInfo(sourceMatch);
        //当前配套信息是否数量变为0，变为0更改为作废状态 11-12更改
        pointPackageDao.updateSourceState(sourceMatch);
        //更新原来的ms_assgin_workbintool_rel数据状态
        pointPackageDao.updateAssginWorkbinToolByMatchInfoStatus(sourceMatch.get("msAoMatchInfoId").toString());
        return responseMsg.setRetCode("200").setMessage("替换成功");
    }

    public ResponseMsg packageTopMatch(HashMap map){
        ResponseMsg responseMsg = new ResponseMsg();
        pointPackageDao.packageTopMatch(map);
        if(Integer.parseInt(map.get("o_Return_Int").toString())==0){
            responseMsg.setRetCode("200").setMessage("配套完成");
        }else{
            responseMsg.setRetCode("201").setMessage("配套失败").setErrorDesc((String)map.get("o_Return_String"));
        }
        return responseMsg;
    }
    /**
     * map:{datas,palletCode,planeNo}
     * datas:[{packageCode,aoCode,palletCode}]
     * **/
    @Transactional
    public HashMap startPalletSort(HashMap map,String ip){
        HashMap ret = new HashMap();
        String planeNo = (String) map.get("planeNo");
        String palletCode = (String) map.get("palletCode");
        List<HashMap> datas = (List<HashMap>) map.get("datas");
        List<HashMap> workbins = new ArrayList<>();
        String groupCode = ComUtil.getId();
        for(HashMap data : datas){
            data.put("planeNo",planeNo);
            data.put("toolCode",palletCode);
            data.put("groupCode",groupCode);
           // workbins.addAll(pointPackageDao.queryMatchWorkbin(data));
            pointPackageDao.insertWorkbinTaskTmp(data);
        }
        //相同工作包重复箱子处理
        pointPackageDao.deleteRepeatWorkbinForPakcage(groupCode);
        workbins = pointPackageDao.getAddTask(groupCode);
        if(workbins.size()==0){
            ret.put("retCode","0");
            ret.put("retMsg","未找到配套的箱子！");
            return ret;
        }
        int workbinTaskCnt = 0;
        for(HashMap workbin : workbins){
            workbin.put("ip",ip);
            if(Objects.isNull(workbin.get("workbinCode"))){
                continue;
            }
            if("312080030000".equals(workbin.get("workbinCode"))){
                //创建大件任务
                int cnt = pointPackageDao.insertBigWorkbinGkLog(workbin);
                workbinTaskCnt+=cnt;
            }else{
                //查询当前任务是否创建
                if(pointPackageDao.queryPalletTaskExists(workbin)>0){
                    pointPackageDao.insertRepeatWorkbinGkLog(workbin);
                }else{
                    //创建箱子任务
                    int cnt = pointPackageDao.insertWorkbinGkLog(workbin);
                    workbinTaskCnt+=cnt;
                }
            }
        }
        if(workbinTaskCnt==0){
            ret.put("retCode","0");
            ret.put("retMsg","托盘对应箱子均不在货架上或存在未完成任务！");
            return ret;
        }
        HashMap toolMap = new HashMap();
        toolMap.put("palletCode",palletCode);
        toolMap.put("ip",ip);
        //创建托盘任务
        pointPackageDao.insertToolGkLog(toolMap);
        //下发任务
        HashMap gkTask = new HashMap();
        gkTask.put("func","sort");
        //下发缓存箱出库指令
        gkTask.put("boxType", "WORKBIN");
        //结束位置
        gkTask.put("endCode", "xyssj" + msConsoleDao.findStartCode(ip, (String) gkTask.get("boxType")));
        //首次下发命令标识符
        gkTask.put("firstCall", "firstCall");
        StringBuffer sb = new StringBuffer();
        //调用封装下发任务
        HashMap wMap = createCommonLog.callWCSInterface(gkTask);
        sb.append("workbin===").append(wMap.get("msg"));
        //下发工作包出库指令
        gkTask.replace("boxType", "TOOL");
        //结束位置
        gkTask.put("endCode", "xyssj" + msConsoleDao.findStartCode(ip, (String) gkTask.get("boxType")));
        //调用封装下发任务
        HashMap tMap = createCommonLog.callWCSInterface(gkTask);
        sb.append(",tool===").append(tMap.get("msg"));
        ret.put("retCode","1");
        ret.put("retMsg","创建任务完毕！");
        ret.put("error",sb.toString());
        return ret;
    }
    @Transactional
    public HashMap assginPallet(){
        HashMap ret = new HashMap();
        try{
            //清理没有创建任务的托盘箱子
            pointPackageDao.clearWorkbinToolRel();
            //写入未分拣的箱子到关系表中，准备和托盘绑定关系
            pointPackageDao.insertAssignWorkbinToolRel();
            //绑定箱子对应的托盘
            List<HashMap> list = pointPackageDao.queryDealWorkbintoolRel();
            for(HashMap data : list){
                //查询此本AO对应的托盘是否被相同架次的工作包使用过
                String toolCode = pointPackageDao.queryToolCodeByPackage(data);
                if(!Objects.isNull(toolCode)){
                    data.put("toolCode",toolCode);
                }else{
                    toolCode = pointPackageDao.queryToolCodeByRule(data);
                    data.put("toolCode",toolCode);
                }
                pointPackageDao.updateToolById(data);
            }
            ret.put("retCode","200");
            ret.put("retMsg","分配成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            ret.put("retCode","201");
            ret.put("retMsg","分配失败");
        }
        return ret;
    }

    public PageInfo queryPalletTask(HashMap map){
        HashMap queryParam = (HashMap) map.get("queryParam");
        HashMap page = (HashMap) map.get("page");
        PageHelper.startPage(Integer.parseInt(page.get("currentPage").toString()),Integer.parseInt(page.get("pageSize").toString()));
        List list = pointPackageDao.queryAssignWorkbintoolRel(queryParam);
        return new PageInfo(list);
    }

    @Transactional
    public ResponseMsg startPalletSortNewModel(HashMap map, String ip){
        String toolCode = (String) map.get("toolCode");
        List<HashMap> workbinCodes = pointPackageDao.queryWorkbinCodes(toolCode);
        if(workbinCodes.size()==0){
            return new ResponseMsg().setRetCode("201").setMessage("当前托盘不存在未分拣的箱子!");
        }
        //创建托盘任务
        HashMap toolMap = new HashMap();
        toolMap.put("palletCode",toolCode);
        toolMap.put("ip",ip);
        //创建托盘任务
        int i = pointPackageDao.insertToolGkLog(toolMap);
        if(i==0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseMsg().setRetCode("201").setMessage("当前托盘不在货架上或存在未完成任务!");
        }
        //更新此托盘状态
        pointPackageDao.updateAssginEotkninTool(toolCode);
        //创建箱子任务
        for(HashMap workbin : workbinCodes){
            workbin.put("ip",ip);
            if(Objects.isNull(workbin.get("workbinCode"))){
                continue;
            }
            if("312080030000".equals(workbin.get("workbinCode"))){
                //创建大件任务
                pointPackageDao.insertBigWorkbinGkLog(workbin);
            }else{
                //查询当前任务是否创建
                if(pointPackageDao.queryTaskNotBackExists(workbin)>0){
                    pointPackageDao.insertSuppleGkLog(workbin);
                }else{
                    //创建箱子任务
                    pointPackageDao.insertWorkbinGkLog(workbin);
                }
            }
        }
        //下发任务
        HashMap gkTask = new HashMap();
        gkTask.put("func","sort");
        //下发缓存箱出库指令
        gkTask.put("boxType", "WORKBIN");
        //结束位置
        gkTask.put("endCode", "xyssj" + msConsoleDao.findStartCode(ip, (String) gkTask.get("boxType")));
        //首次下发命令标识符
        gkTask.put("firstCall", "firstCall");
        StringBuffer sb = new StringBuffer();
        //调用封装下发任务
        HashMap wMap = createCommonLog.callWCSInterface(gkTask);
        sb.append("workbin===").append(wMap.get("msg"));
        //下发工作包出库指令
        gkTask.replace("boxType", "TOOL");
        //结束位置
        gkTask.put("endCode", "xyssj" + msConsoleDao.findStartCode(ip, (String) gkTask.get("boxType")));
        //调用封装下发任务
        HashMap tMap = createCommonLog.callWCSInterface(gkTask);
        sb.append(",tool===").append(tMap.get("msg"));
        return new ResponseMsg().setRetCode("200").setMessage("操作成功").setErrorDesc(sb.toString());
    }

    public List<HashMap> searchInventoryMaterialByWorkbinCode(HashMap map){
        return pointPackageDao.searchInventoryMaterialByWorkbinCode(map);
    }
    @Transactional
    public ResponseMsg addHcx(HashMap map, String ip){
        log.info(map.toString());
        String msAoMatchInfoId = ComUtil.getId();
        map.put("msAoMatchInfoId",msAoMatchInfoId);
        //插入一条新的配套数据 ms_ao_match_info
        pointPackageDao.addNewAoMatchInfo(map);
        //插入一条 ms_assgin_workbintool_rel
        pointPackageDao.insertAssignWorkbinToolRelByMatchInfoId(map);
        //更新 原来ms_ao_match_info表数据
        pointPackageDao.updatePreMatchInfo(map);
        //更新原来的ms_assgin_workbintool_rel数据状态
        pointPackageDao.updateAssginWorkbinToolRelStatus(map);
        //创建日志任务
        //查询当前任务是否创建
        HashMap workbin = new HashMap();
        workbin.put("workbinCode",map.get("workbinCode"));
        workbin.put("ip",ip);
        if(pointPackageDao.queryTaskNotBackExists(workbin)>0){
            pointPackageDao.insertSuppleGkLog(workbin);
        }else{
            //创建箱子任务
            pointPackageDao.insertWorkbinGkLog(workbin);
        }
        //给wcs下达指令
        //下发任务
        HashMap gkTask = new HashMap();
        gkTask.put("func","sort");
        //下发缓存箱出库指令
        gkTask.put("boxType", "WORKBIN");
        //结束位置
        gkTask.put("endCode", "xyssj" + msConsoleDao.findStartCode(ip, (String) gkTask.get("boxType")));
        //首次下发命令标识符
        gkTask.put("firstCall", "firstCall");
        StringBuffer sb = new StringBuffer();
        //调用封装下发任务
        HashMap wMap = createCommonLog.callWCSInterface(gkTask);
        sb.append("workbin===").append(wMap.get("msg"));
        return new ResponseMsg().setRetCode("200").setMessage("操作成功").setErrorDesc(sb.toString());
    }
    @Transactional
    public ResponseMsg replaceToolCode(HashMap map){
        pointPackageDao.replaceToolCode(map);
        return new ResponseMsg().setRetCode("200").setMessage("操作成功");
    }

    @Transactional
    public ResponseMsg replaceToolByHandle(HashMap map){
        pointPackageDao.replaceToolByHandle(map);
        return new ResponseMsg().setRetCode("200").setMessage("操作成功");
    }
}
